package dai.samples.rabbit.retry.receiver;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import dai.samples.rabbit.entity.User;
import dai.samples.rabbit.retry.config.FailedConfig;
import dai.samples.rabbit.retry.config.RetryConfig;
import dai.samples.rabbit.retry.config.WorkConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 *
 * @author daify
 * @date 2019-08-14
 **/
@Component
@Slf4j
public class WorkReceiver {

    @Autowired RabbitTemplate rabbitTemplate;
    
    /**
     * queues是指要监听的队列的名字
     * @param user
     */
    @RabbitListener(queues = WorkConfig.WORK_QUEUE,
            errorHandler = "retryReceiverListenerErrorHandler")
    public void receiveDirect(User user,
                              Channel channel,
                              Message message) throws Exception {
        try {
            log.info("【WorkReceiver监听到消息】" + JSON.toJSONString(user));
            Integer retry = user.getRetry();
            String id = user.getId();
            log.info("重试次数：{}",retry);
            if (retry < 3 || "1".equals(id)) {
                user.setRetry(retry + 1);
                throw new RuntimeException("进入重试");
            }
            log.info("消费成功");
        } catch (Exception e) {
            log.info("开始重试");
            if (user.getRetry() > 3) {
                rabbitTemplate.convertAndSend(
                        FailedConfig.FAILED_EXCHANGE,
                        // routingKey
                        FailedConfig.FAILED_KEY,
                        user);
                log.info("receiver failed");
            } else {
                rabbitTemplate.convertAndSend(
                        RetryConfig.RETRY_EXCHANGE,
                        // routingKey
                        RetryConfig.RETRY_KEY,
                        user);
                log.info("receiver error");
            }
        }
    }

}
